package org.example.thread.testSimpleDateFormat;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.util.DateUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author liyishan
 * @date 2023/8/3 13:52
 * @apiNote
 */

public class SimpleDateFormatTest01 {
    //执行总次数
    private static final int EXECUTE_COUNT = 1000;
    //同时运行的线程数量
    private static final int THREAD_COUNT = 20;
    //SimpleDateFormat对象
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    //Lock
    private static Lock lock = new ReentrantLock();
    //ThreadLocal
    private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>(){
        @Override
        protected DateFormat initialValue(){
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };
    //DateTimeFormatter
    private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");


    public static void main(String[] args)throws ExecutionException,InterruptedException {
        test8();
    }

    /**
     * 不安全示例
     * @throws ExecutionException
     * @throws InterruptedException
     * 不安全原因： SimpleDateFormat 是继承自DateFormat类，DateFormat类中维护了一个全局的Calendar变量
     *     public Date parse(String text, ParsePosition pos) 方法中的核心是              parsedDate = calb.establish(calendar).getTime();
     *     java.text.CalendarBuilder#establish(java.util.Calendar) 方法中先后调用了cal.clear() 和 cal.set(),也就是先清除cal对象中设置的值，再重新设置新的值
     *     由于Calendar内部并没有线程安全机制，并且这两个操作也不都是原子性的，所以当多个线程同时操作一个SimpleDateFormat时就会引起cal的值混乱  format() 方法也存在同样的问题
     *     因此 不安全的根本原因是DateFormat类中的Calendar对象被多线程共享，而Calendar对象本身不支持线程安全
     */
    private static void test()throws ExecutionException,InterruptedException{
        final Semaphore semaphore = new Semaphore(THREAD_COUNT);
        final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i = 0;i<EXECUTE_COUNT;i++){
            executorService.execute(() ->{
                try{
                    semaphore.acquire();
                    try{
                        sdf.parse("2020-01-01");
                    }catch (ParseException e){
                        System.out.println("线程："+Thread.currentThread().getName()+" 执行异常");
                        e.printStackTrace();
                        System.exit(1);
                    }catch (NumberFormatException e){
                        System.out.println("线程："+Thread.currentThread().getName()+" 执行异常");
                        e.printStackTrace();
                        System.exit(1);
                    }
                }catch (InterruptedException e){
                    System.out.println("信号量错误");
                    e.printStackTrace();
                    System.exit(1);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println("所有线程格式化日期成功");
    }

    /**
     * 解决方法1： 局部变量法  将SimpleDateFormat类对象定义在parse(String) 方法的上面
     * @throws ExecutionException
     * @throws InterruptedException
     */
    private static void test2()throws ExecutionException,InterruptedException{
        final Semaphore semaphore = new Semaphore(THREAD_COUNT);
        final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i = 0;i<EXECUTE_COUNT;i++){
            executorService.execute(() ->{
                try{
                    semaphore.acquire();
                    try{
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        simpleDateFormat.parse("2020-01-01");
                    }catch (ParseException e){
                        System.out.println("线程："+Thread.currentThread().getName()+" 执行异常");
                        e.printStackTrace();
                        System.exit(1);
                    }catch (NumberFormatException e){
                        System.out.println("线程："+Thread.currentThread().getName()+" 执行异常");
                        e.printStackTrace();
                        System.exit(1);
                    }
                    semaphore.release();
                }catch (InterruptedException e){
                    System.out.println("信号量错误");
                    e.printStackTrace();
                    System.exit(1);
                }
                countDownLatch.countDown();

            });
            countDownLatch.await();
            executorService.shutdown();
            System.out.println("所有线程格式化日期成功");
        }
    }

    /**
     * synchronized   影响性能
     * @throws ExecutionException
     * @throws InterruptedException
     */
    private static void test3()throws ExecutionException,InterruptedException{
        final Semaphore semaphore = new Semaphore(THREAD_COUNT);
        final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i = 0;i<EXECUTE_COUNT;i++){
            executorService.execute(()->{
                try{
                    semaphore.acquire();
                    try{
                        synchronized (sdf){
                            sdf.parse("2020-01-01");
                        }
                    }catch (ParseException e){
                        System.out.println("线程："+Thread.currentThread().getName()+" 执行异常");
                        e.printStackTrace();
                        System.exit(1);
                    }catch (NumberFormatException e){
                        System.out.println("线程："+Thread.currentThread().getName()+" 执行异常");
                        e.printStackTrace();
                        System.exit(1);
                    }
                    semaphore.release();
                }catch (InterruptedException e){
                    System.out.println("信号量错误");
                    e.printStackTrace();
                    System.exit(1);
                }
                countDownLatch.countDown();
            });
            countDownLatch.await();
            executorService.shutdown();
            System.out.println("所有线程格式化日期成功");
        }
    }


    /**
     * 全局静态变量作为加锁和释放锁的句柄
     * @throws ExecutionException
     * @throws InterruptedException
     */
    private static void test4()throws ExecutionException,InterruptedException{
        final Semaphore semaphore = new Semaphore(THREAD_COUNT);
        final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i = 0;i<EXECUTE_COUNT;i++){
            executorService.execute(() ->{
                try{
                    semaphore.acquire();
                    try{
                        lock.lock();
                        sdf.parse("2020-01-01");
                    }catch (ParseException e){
                        System.out.println("线程："+Thread.currentThread().getName()+" 执行异常");
                        e.printStackTrace();
                        System.exit(1);
                    }catch (NumberFormatException e){
                        System.out.println("线程："+Thread.currentThread().getName()+" 执行异常");
                        e.printStackTrace();
                        System.exit(1);
                    }finally {
                        lock.unlock();
                    }
                    semaphore.release();
                }catch (InterruptedException e){
                    System.out.println("信号量错误");
                    e.printStackTrace();
                    System.exit(1);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println("所有线程格式化日期成功");
    }


    /**
     * 将每个线程使用的SimplateDateFormat副本保存在ThreadLocal中，各个线程在使用时互不干扰
     * @throws ExecutionException
     * @throws InterruptedException
     */
    private static void test5()throws ExecutionException,InterruptedException{
        final Semaphore semaphore = new Semaphore(THREAD_COUNT);
        final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i = 0;i<EXECUTE_COUNT;i++){
            executorService.execute(() ->{
                try{
                    semaphore.acquire();
                    try{
                        threadLocal.get().parse("2022-02-02");
                    }catch (ParseException e){
                        System.out.println("线程："+Thread.currentThread().getName()+" 执行异常");
                        e.printStackTrace();
                        System.exit(1);
                    }catch (NumberFormatException e){
                        System.out.println("线程："+Thread.currentThread().getName()+" 执行异常");
                        e.printStackTrace();
                        System.exit(1);
                    }
                    semaphore.release();
                }catch (InterruptedException e){
                    System.out.println("信号量错误");
                    e.printStackTrace();
                    System.exit(1);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println("所有线程格式化日期成功");
    }

    /**
     * DateTimeFormatter类是线程安全的，可以在高并发场景下直接使用DateTimeFormatter类来处理日期的格式化操作。
     * @throws InterruptedException
     */
    private static void test6()throws InterruptedException{
        final Semaphore semaphore = new Semaphore(THREAD_COUNT);
        final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i = 0;i<EXECUTE_COUNT;i++){
            executorService.execute(() ->{
                try{
                    semaphore.acquire();
                    try{
                        LocalDate.parse("2022-01-01", formatter);
                    }catch(Exception e){
                        System.out.println("线程："+Thread.currentThread().getName()+" 执行异常");
                        e.printStackTrace();
                        System.exit(1);
                    }
                    semaphore.release();
                }catch(InterruptedException e){
                    System.out.println("信号量错误");
                    e.printStackTrace();
                    System.exit(1);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println("所有线程格式化日期成功");
    }


    /**
     * Hutool   DateUtil.parse("2022-01-01","yyyy-MM-dd");
     * @throws InterruptedException
     */
    private static void test7()throws InterruptedException{
        final Semaphore semaphore = new Semaphore(THREAD_COUNT);
        final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i = 0;i<EXECUTE_COUNT;i++){
            executorService.execute(() ->{
                try{
                    semaphore.acquire();
                    try{
                        DateUtil.parse("2022-01-01","yyyy-MM-dd");
                    }catch(Exception e){
                        System.out.println("线程："+Thread.currentThread().getName()+" 执行异常");
                        e.printStackTrace();
                        System.exit(1);
                    }
                    semaphore.release();
                }catch(InterruptedException e){
                    System.out.println("信号量错误");
                    e.printStackTrace();
                    System.exit(1);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println("所有线程格式化日期成功");
    }



    /**
     * fastjson2     DateUtils.format(new Date(),"yyyy-MM-dd");
     * @throws InterruptedException
     */
    private static void test8()throws InterruptedException{
        final Semaphore semaphore = new Semaphore(THREAD_COUNT);
        final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i = 0;i<EXECUTE_COUNT;i++){
            executorService.execute(() ->{
                try{
                    semaphore.acquire();
                    try{
                        DateUtils.format(new Date(),"yyyy-MM-dd");
                    }catch(Exception e){
                        System.out.println("线程："+Thread.currentThread().getName()+" 执行异常");
                        e.printStackTrace();
                        System.exit(1);
                    }
                    semaphore.release();
                }catch(InterruptedException e){
                    System.out.println("信号量错误");
                    e.printStackTrace();
                    System.exit(1);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println("所有线程格式化日期成功");
    }


}
